package com.example.bpmn.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Tag(name = "人工任务接口")
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    @Operation(summary = "获取用户任务列表")
    @GetMapping
    public ResponseEntity<List<Map<String, Object>>> getTasks(
            @RequestParam(required = false) String assignee,
            @RequestParam(required = false) String candidateGroup) {
        
        List<Task> tasks;
        if (assignee != null) {
            tasks = taskService.createTaskQuery()
                    .taskAssignee(assignee)
                    .list();
        } else if (candidateGroup != null) {
            tasks = taskService.createTaskQuery()
                    .taskCandidateGroup(candidateGroup)
                    .list();
        } else {
            tasks = taskService.createTaskQuery()
                    .list();
        }
        
        List<Map<String, Object>> taskList = tasks.stream()
                .map(this::convertTaskToMap)
                .collect(Collectors.toList());
                
        return ResponseEntity.ok(taskList);
    }
    
    @Operation(summary = "完成人工任务")
    @PostMapping("/{taskId}/complete")
    public ResponseEntity<Void> completeTask(
            @PathVariable String taskId,
            @RequestBody Map<String, Object> variables) {
        taskService.complete(taskId, variables);
        return ResponseEntity.ok().build();
    }
    
    @Operation(summary = "认领任务")
    @PostMapping("/{taskId}/claim")
    public ResponseEntity<Void> claimTask(
            @PathVariable String taskId,
            @RequestParam String userId) {
        taskService.claim(taskId, userId);
        return ResponseEntity.ok().build();
    }
    
    private Map<String, Object> convertTaskToMap(Task task) {
        Map<String, Object> taskMap = new HashMap<>();
        taskMap.put("id", task.getId());
        taskMap.put("name", task.getName());
        taskMap.put("assignee", task.getAssignee());
        taskMap.put("created", task.getCreateTime());
        taskMap.put("processInstanceId", task.getProcessInstanceId());
        
        // 获取业务关键字
        Object orderId = taskService.getVariable(task.getId(), "orderId");
        taskMap.put("orderId", orderId);
        
        return taskMap;
    }
} 